package net.cyue.web.easyquery.core.config.toml;

import net.cyue.util.StreamUtil;
import net.cyue.util.StringUtil;
import net.cyue.web.easyquery.core.config.AdditionalConfigItem;
import net.cyue.web.easyquery.core.config.ConfigException;
import net.cyue.web.easyquery.core.config.ConfigItemValue;
import net.cyue.web.easyquery.core.config.EasyQueryConfiguration;
import org.tomlj.Toml;
import org.tomlj.TomlParseResult;
import org.tomlj.TomlTable;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Set;

public class EasyQueryTOMLConfiguration extends EasyQueryConfiguration {

    private String toml;

    public EasyQueryTOMLConfiguration(String toml) {
        super();
        this.toml = toml;
    }

    public static EasyQueryTOMLConfiguration fromStream(InputStream inputStream)
        throws IOException, ConfigException
    {
        return fromTOML(StreamUtil.readAsString(inputStream));
    }

    public static EasyQueryTOMLConfiguration fromTOML(String toml) throws ConfigException {
        EasyQueryTOMLConfiguration configuration = new EasyQueryTOMLConfiguration(toml);
        configuration.readTOML(toml);
        return configuration;
    }

    public void readTOML(String toml) throws ConfigException {
        this.toml = toml;
        this.configItemValueMap = new HashMap<>();
        TomlParseResult tomlResult = Toml.parse(toml);

        // additional 配置
        AdditionalConfigItem[] additionalConfigItems = this.getAdditionalConfigItems();
        for (AdditionalConfigItem item : additionalConfigItems) {
            String key = item.getFullName();
            String value = tomlResult.getString(key);
            if (value != null) {
                this.configItemValueMap.put(
                    key,
                    TOMLConfigItemValue.fromKeyValue(item.getFullName(), value)
                );
            }
        }

        // api 配置
        Set<String> keySet = tomlResult.keySet();
        Set<String> additionalConfigItemKeySet = this.getAdditionalConfigItemNameSet();
        for (String key : keySet) {
            // 跳过 additional 配置
            if (key.equalsIgnoreCase("database")) {
                continue;
            } else if (key.equalsIgnoreCase("server")) {
                continue;
            } else if (key.equalsIgnoreCase("application")) {
                continue;
            } else if (additionalConfigItemKeySet.contains(key)) {
                continue;
            }

            TomlTable table = tomlResult.getTable(key);
            if (table != null) {
                ConfigItemValue configItemValue = TOMLConfigItemValue.fromTable(table);
                this.configItemValueMap.put(key, configItemValue);
            }
        }
    }

    public String toJSON() {
        if (StringUtil.isBlank(this.toml)) {
            return null;
        }
        return Toml.parse(this.toml).toJson();
    }
}
